package il.technion.cs236369.proxy;

import il.technion.cs236369.database.Cache;
import il.technion.cs236369.database.ICache;
import il.technion.cs236369.database.SterilizedCache;
import il.technion.cs236369.proxy.communication.http.HttpProxyServer;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;

/**
 * The main Http Proxy class
 * @author itamar talmi 0396055979 itamar.talmi@gmail.com , ofir haviv 300228921 havivi1986@gmail.com
 *
 */
public class HttpProxy extends AbstractHttpProxy {

	@Inject
	HttpProxy(SocketFactory sockFactory, ServerSocketFactory srvSockFactory,

	@Named("httproxy.net.port") int port,
			@Named("httproxy.db.url") String dbURL,
			@Named("httproxy.db.name") String dbName,
			@Named("httproxy.db.table") String tblName,
			@Named("httproxy.db.username") String dbUsername,
			@Named("httproxy.db.password") String dbPassword,
			@Named("httproxy.db.driver") String dbDriver)
			throws ClassNotFoundException {
		super(sockFactory, srvSockFactory, port, dbURL, dbName, tblName,
				dbUsername, dbPassword, dbDriver);

		try {
			cache = new Cache(dbDriver, dbURL, dbName, tblName, dbUsername,
					dbPassword);
		} catch (SQLException e) {
			System.err.println("Error while tring to connect to the cache table. Not Using cache");
			cache = new SterilizedCache();
		}
	}

	private HttpProxyServer proxyServer;
	private ICache cache;

	@Override
	public void bind() throws IOException {
		this.proxyServer = new HttpProxyServer(this.srvSockFactory, port,	new ProxyHttpRequestHandler(sockFactory, cache));

	}

	@Override
	public void start() {

		while (true) {
			try {
				proxyServer.getNewHttpRequest(); 
			} catch (Exception e) {
				System.err.println("Error accure while tring to get new request from the client");
				//System.err.println("Error in HttpProxy.start");
				//e.printStackTrace();
			} 
		}

	}

	public static void main(String[] args) throws Exception {
		Properties p = new Properties();
		p.load(new FileInputStream("config"));
		Injector inj = Guice.createInjector(new HttpProxyModule(p));
		// Injector inj = Guice.createInjector(new HttpProxyModule());
		IHttpProxy proxy = inj.getInstance(HttpProxy.class);
		proxy.bind();
		proxy.start();

	}
	
}
